package cn.iocoder.yudao.module.xkfz.service.operationalPerformance.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.xkfz.domain.entity.basic.DepartmentScore;
import cn.iocoder.yudao.module.xkfz.domain.entity.basic.DeptBasic;
import cn.iocoder.yudao.module.xkfz.domain.entity.basic.IndicatorTree;
import cn.iocoder.yudao.module.xkfz.domain.entity.operationalPerformance.MetricDirectScore;
import cn.iocoder.yudao.module.xkfz.domain.excel.entity.*;
import cn.iocoder.yudao.module.xkfz.domain.po.operationalPerformance.MetricDirectScorePo;
import cn.iocoder.yudao.module.xkfz.mapper.basic.DeptBasicMapper;
import cn.iocoder.yudao.module.xkfz.mapper.basic.IndicatorTreeMapper;
import cn.iocoder.yudao.module.xkfz.mapper.clinicalHealthCare.ElementDataMonthXkrcMapper;
import cn.iocoder.yudao.module.xkfz.mapper.excel.*;
import cn.iocoder.yudao.module.xkfz.mapper.operationalPerformance.MetricDirectScoreMapper;
import cn.iocoder.yudao.module.xkfz.service.operationalPerformance.MetricDirectScoreService;
import cn.iocoder.yudao.module.xkfz.util.BuildIndicatorTree;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MetricDirectScoreServiceImpl implements MetricDirectScoreService {


    @Autowired
    MetricDirectScoreMapper metricDirectScoreMapper;
    @Autowired
    IndicatorTreeMapper indicatorTreeMapper;

    @Autowired
    DeptBasicMapper deptBasicMapper;
    @Autowired
    private GuidelinesAndConsensusMapper guidelinesAndConsensusMapper;
    @Autowired
    private InventionPatentMapper inventionPatentMapper;
    @Autowired
    private LeadMulticenterProjectsMapper leadMulticenterProjectsMapper;
    @Autowired
    private PatentTransferMapper patentTransferMapper;
    @Autowired
    private ProjectInfoMapper projectInfoMapper;
    @Autowired
    private TechnologicalOutputSciMapper technologicalOutputSciMapper;
    @Autowired
    private KsIndicatorSelectConfigMapper ksIndicatorSelectConfigMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertMetricDirectScore(List<MetricDirectScorePo> metricDirectScorePo) {
        try {
            metricDirectScoreMapper.deleteByMap(new HashMap<String,Object>(){{
                put("INDICATOR_ID", metricDirectScorePo.get(0).getIndicatorId());
                put("YEAR",metricDirectScorePo.get(0).getYear());
            }});
            List<MetricDirectScore> metricDirectScores = BeanUtil.copyToList(metricDirectScorePo, MetricDirectScore.class);
            metricDirectScoreMapper.insertBatch(metricDirectScores);
            // 操作成功
            log.info("insertMetricDirectScore: 数据插入成功");
            return true;
        } catch (Exception e) {
            // 异常处理和日志记录
            log.error("insertMetricDirectScore: 数据插入失败", e);
            throw e; // 将异常抛出，让调用者知道操作失败的原因
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMetricDirectScore(List<MetricDirectScorePo> metricDirectScorePo) {
//        Map<String,Object> map = new HashMap<String,Object>(){{
//            put("ksId", metricDirectScorePo.get(0).getKsId());
//            put("year",metricDirectScorePo.get(0).getYear());
//        }};
        // 删除这个指标的数据
        metricDirectScoreMapper.deleteByMap(new HashMap<String,Object>(){{
            put("INDICATOR_ID", metricDirectScorePo.get(0).getIndicatorId());
            put("YEAR",metricDirectScorePo.get(0).getYear());
        }});
        //重新新增
        MetricDirectScoreServiceImpl metricDirectScoreService = (MetricDirectScoreServiceImpl ) AopContext.currentProxy();
        metricDirectScoreService.insertMetricDirectScore(metricDirectScorePo);
        return false;
    }

    @Override
    public List<MetricDirectScore> queryIndicatorDeptScore(String indicatorId,String year) {

        List<MetricDirectScore> metricDirectScoreList =
                metricDirectScoreMapper.selectList(
                        new LambdaQueryWrapperX<MetricDirectScore>()
                                .eq(MetricDirectScore::getIndicatorId, indicatorId)
                                .eq(MetricDirectScore::getYear, year));
        return metricDirectScoreList;
    }

    @Override
    public List<IndicatorTree> queryIndicatorScore(Map<String,String> map) {
        //String indicatorName = map.get("indicatorName");
        String year = map.get("year");
        List<IndicatorTree> indicatorTreeList = indicatorTreeMapper.selectList("year",year);
        //通过层级算没一层指标的得分情况
        List<IndicatorTree> indicatorTrees = BuildIndicatorTree.buildTree(indicatorTreeList);
//        indicatorTrees = indicatorTrees.stream().filter(indicatorTree ->
//                indicatorTree.getIndicatorName().equals(indicatorName)).collect(Collectors.toList());
        //过滤最终结果数据
        List<DeptBasic> theCandidacyDepartment = getTheCandidacyDepartment(map);
        indicatorTrees = indicatorTrees(theCandidacyDepartment,indicatorTrees);
        return indicatorTrees;
    }

    /**
     * 获取参选分组的部门（每个专题参选部门也不一样，后续需要剔除掉没有参选的部门，单独一张表记录没有参选的部门）
     * @param map
     * @return
     */
    public List<DeptBasic> getTheCandidacyDepartment(Map<String,String> map) {
        //获取参选部门
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("year", map.get("year"));
        //分组标志
        if(map.get("groupType")!= null){
            queryWrapper.eq("type", map.get("groupType"));
        }
        List<DeptBasic> deptBasicList = deptBasicMapper.selectList(queryWrapper);
        return deptBasicList;
    }

    public   List<IndicatorTree> indicatorTrees(List<DeptBasic> deptBasicList,List<IndicatorTree> indicatorTrees){
        for (IndicatorTree indicatorTree : indicatorTrees) {
            //todo 剔除每个专题的科室

            //todo 过滤分组
            List<DepartmentScore> departmentScores = indicatorTree.getDepartmentScores();
            if(departmentScores!=null){
                List<DepartmentScore> filteredScores = departmentScores.stream()
                        .filter(ds -> deptBasicList.stream()
                                .anyMatch(db -> db.getKsName().equals(ds.getKsName())))
                        .collect(Collectors.toList());
                indicatorTree.setDepartmentScores(filteredScores);
            }

        }
        return indicatorTrees;
    }

    @Override
    public List<Map<String,Object>> queryIndicatorScoreAll(Map<String, String> map) {
        //参评年份
        String year = map.get("year");
        List<IndicatorTree> indicatorTreeList = indicatorTreeMapper.selectList("year",year);
        if(indicatorTreeList.size()!=0){
            List<IndicatorTree> indicatorTrees = BuildIndicatorTree.buildTree(indicatorTreeList);
            String[] indicatorNames = indicatorTrees.stream().
                    map(IndicatorTree::getIndicatorName).toArray(String[]::new);
            List<DeptBasic> deptBasicList = deptBasicMapper.selectList("YEAR", year);
            List<Map<String, Object>> resultList = new ArrayList<>();
            Map<String, Object> indicatorMaps = new HashMap<>();
            indicatorMaps.put("indicatorNames", Arrays.stream(indicatorNames).toArray());
            resultList.add(indicatorMaps);
            for (DeptBasic deptBasic : deptBasicList) {
                Map<String, Object> deptMap = new HashMap<>();
                List<DepartmentScore> ksDepartmentScores = getDepartmentScoresForDept(indicatorTrees, deptBasic);
                double sum = ksDepartmentScores.stream()
                        .mapToDouble(value -> Double.valueOf(value.getScore()))
                        .sum();
                deptMap.put("ksName", deptBasic.getKsName());
                deptMap.put("scoreList", ksDepartmentScores);
                deptMap.put("allList", sum);
                resultList.add(deptMap);
            }
            return resultList;
        }
        return null;
    }

    @Override
    public List<IndicatorTree> querySubIndicatorByParent(String pIndicatorId, String year, String ksName) {
        //查询所有的父亲下所有子指标id
        IndicatorTree parentTreeNode = new IndicatorTree();
        parentTreeNode.setId(Long.valueOf(pIndicatorId));
        ArrayList<IndicatorTree> allLeaves = new ArrayList<>();

        getLeafIndicators(Arrays.asList(parentTreeNode), year, allLeaves);
        List<KsIndicatorSelectConfig> ksIndicatorSelectConfigs = ksIndicatorSelectConfigMapper.selectList();
        Map<Long, KsIndicatorSelectConfig> selectMap = ksIndicatorSelectConfigs.stream()
                .collect(Collectors.toMap(
                        KsIndicatorSelectConfig::getIndexId, // Key: indexId
                        config -> config,                    // Value: KsIndicatorSelectConfig 对象
                        (existing, replacement) -> existing  // 如果 key 冲突，保留已存在的值（第一个）
                ));
        //填充查询路径
        Iterator<IndicatorTree> iterator = allLeaves.iterator();
        while (iterator.hasNext()) {
            IndicatorTree allLeaf = iterator.next();
            KsIndicatorSelectConfig config = selectMap.get(allLeaf.getId());

            if (config != null) {
                allLeaf.setSelectPath(config.getSelectPath());
            } else {
                // 使用迭代器安全移除
                iterator.remove();
            }
        }
        return allLeaves;
    }



    private List<IndicatorTree> getLeafIndicators(List<IndicatorTree> indicatorTrees,
                                                  String year,
                                                  List<IndicatorTree> allLeafIndicators) {
        if (CollectionUtil.isEmpty(indicatorTrees)) {
            return allLeafIndicators;
        }

        // 1. 只查询当前层级的直接子节点（精确控制层级）
        List<Long> currentLevelParentIds = indicatorTrees.stream()
                .map(IndicatorTree::getId)
                .collect(Collectors.toList());

        LambdaQueryWrapperX<IndicatorTree> wrapperX = new LambdaQueryWrapperX<>();
        wrapperX.in(IndicatorTree::getParentId, currentLevelParentIds);
        wrapperX.eq(IndicatorTree::getYear, year);
        List<IndicatorTree> directChildren = indicatorTreeMapper.selectList(wrapperX);

        // 2. 分离叶子节点和非叶子节点
        Map<Boolean, List<IndicatorTree>> partitionedNodes = indicatorTrees.stream()
                .collect(Collectors.partitioningBy(
                        node -> directChildren.stream()
                                .noneMatch(child -> child.getParentId().equals(node.getId()))
                ));

        // 3. 添加当前层的叶子节点
        allLeafIndicators.addAll(partitionedNodes.get(true));

        // 4. 递归处理非叶子节点（它们的子节点）
        if (!partitionedNodes.get(false).isEmpty()) {
            getLeafIndicators(directChildren, year, allLeafIndicators);
        }

        return allLeafIndicators;
    }
    private List<DepartmentScore> getDepartmentScoresForDept(List<IndicatorTree> indicatorTrees, DeptBasic deptBasic) {
        List<DepartmentScore> departmentScores = new ArrayList<>();
        for (IndicatorTree indicatorTree : indicatorTrees) {
            List<DepartmentScore> scores = indicatorTree.getDepartmentScores();
            if(scores==null){
                departmentScores.add(new DepartmentScore(deptBasic.getKsName(),"0"));
            }else{
                List<DepartmentScore> departmentScoreList = scores.stream()
                        .filter(departmentScore -> Objects.equals(departmentScore.getKsName(), deptBasic.getKsName()))
                        .collect(Collectors.toList());
                if(departmentScoreList.size()!=0){
                    departmentScores.addAll(departmentScoreList);
                }else{
                    departmentScores.add(new DepartmentScore(deptBasic.getKsName(),"0"));
                }
            }
        }
        return departmentScores;
    }
}
